/*
 * Powered By Rubyliu
 * QQ:876181
 * Since 2012 - 2013
 */

package com.henme.crm.web.product;

import com.henme.crm.entity.product.Product;
import com.henme.crm.service.product.ProductService;
import com.henme.crm.util.dwz.AjaxDone;
import com.henme.crm.util.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * @author Ruby liu
 * @version 1.0
 * @since 1.0
 */
@Controller
@RequestMapping("/product")
public class ProductController   {
	
	@Autowired
	private ProductService productService;
	
	/**
	 * page 获得从页面传过来的分页信息
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(@ModelAttribute("page") Page<Product> page,
			@ModelAttribute("product") Product product,
            @RequestParam(value = "navtabid", required = false) String navtabid,
			Model model) {
        //从页面获得的是
        if(product!=null&&product.getProductCategory()!=null){
            product.setCategoryid(product.getProductCategory().getId());
        }
		page.setT(product);
		page=productService.getProductList(page);
		model.addAttribute("page", page);
		model.addAttribute("product", product);
		model.addAttribute("navtabid", navtabid);
		return "product/product/list";
	}
	
	/**
	 * 编辑页面
	 * @param model
	 * @param id
	 * @param navtabid
	 * @return
	 */
	@RequestMapping(value="/edit/{id}")
	public String prepare(Model model,@PathVariable("id") Long id,
			@RequestParam("navtabid") String navtabid
		) {
		model.addAttribute("navtabid", navtabid);
		model.addAttribute("product", productService.selectProduct(id));
		return "product/product/edit";
	}


	
	/**
	 * 保存更新
	 * @param product
	 * @param navtabid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/update")
	public AjaxDone update(@ModelAttribute("product")Product product,
			@RequestParam("navtabid") String navtabid
			) 
	{
        product.setCategoryid(product.getProductCategory().getId()); //设置产品类别
        product.setUpdateTime(new Date());   //修改最后修改时间
		productService.updateProduct(product);
		AjaxDone a=new AjaxDone();
		a.setStatusCode("200");
		a.setCallbackType("closeCurrent");
		a.setMessage("更新成功");
		a.setNavTabId(navtabid); //重新加载这个nav
		return a;
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete/{id}")
	public AjaxDone delete(@PathVariable("id") Long id) {
		productService.deleteProduct(id);
		AjaxDone a=new AjaxDone();
		a.setStatusCode("200");
		a.setMessage("删除成功");
		return a;
	}
	
	/**
	 * 新增页面
	 * @param model
	 * @param navtabid
	 * @return
	 */
	@RequestMapping("/add")
	public String add(Model model,@RequestParam("navtabid") String navtabid) {
		model.addAttribute("navtabid", navtabid);
		return "product/product/add";
	}

    /**
     * 查找带回
     * @param model
     * @return
     */
    @RequestMapping("/lookup")
    public String lookup(Model model) {
        return "product/product/lookup";
    }


	/**
	 * 保存新增
	 * @param product
	 * @param navtabid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/insert")
	public AjaxDone insert(@ModelAttribute("product")Product product,
                           HttpServletRequest request,
			@RequestParam("navtabid") String navtabid) {
        product.setCategoryid(product.getProductCategory().getId());
        product.setCreateTime(new Date());
        String fileArray=request.getParameter("fileArray");
		productService.insertProduct(product,fileArray);

		AjaxDone a=new AjaxDone();
		a.setStatusCode("200");
		a.setCallbackType("closeCurrent");
		a.setMessage("新增成功");
		a.setForwardUrl(""); 
		a.setNavTabId(navtabid); //重新加载这个nav
		return a;
	}

    @ResponseBody
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request){
        String responseStr="";
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 文件保存路径
        String ctxPath=request.getSession().getServletContext().getRealPath("/")+ File.separator+"uploadFiles";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());
        ctxPath += File.separator + ymd + File.separator;
        // 创建文件夹
        File file = new File(ctxPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = null;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            fileName = mf.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            // 重命名文件
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
            File uploadFile = new File(ctxPath + newFileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                responseStr=newFileName;
            } catch (IOException e) {
                responseStr="xxx";
                e.printStackTrace();
            }
        }
        return responseStr;
    }

}

